package com.hh.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hh.common.BaseResponse;
import com.hh.common.ResultUtils;
import com.hh.entity.domain.Blog;
import com.hh.entity.vo.BlogVO;
import com.hh.recommend.ItemCFRecommender;
import com.hh.service.BlogService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * com.hh.controller
 *
 * @author
 * @version 0.0.1
 * @date 2025/7/25
 **/
@RestController
@RequestMapping("/recommend")
public class RecommendController {

    @Resource
    private ItemCFRecommender recommender;

    @Resource
    private BlogService blogService;

    @GetMapping("/for-user/{userId}")
    public BaseResponse<Page<BlogVO>> getUserRecommendation(
            @PathVariable Long userId, @RequestParam(defaultValue = "10") int topN, HttpServletRequest request) {

        List<Long> recommendations = recommender.recommendItems(userId, topN);
        List<Blog> blogList = recommendations.stream().map(blogId -> blogService.getById(blogId)).collect(Collectors.toList());
        Page<Blog> blogPage = new Page<>(1, 10);
        blogPage.setRecords(blogList);
        Page<BlogVO> blogVoPage = blogService.getBlogVoPage(blogPage, request);
        if (blogVoPage == null) {
            blogVoPage = new Page<>();
            blogVoPage.setRecords(Collections.emptyList());
        }
        return ResultUtils.success(blogVoPage);
    }

    // 冷启动推荐（基于热门物品）
    @GetMapping("/hot")
    public BaseResponse<List<Long>> getHotItems(
            @RequestParam(defaultValue = "10") int topN) {

        // 简化实现：实际应从Redis获取缓存的热门商品
        List<Long> hotItems = Arrays.asList(1001L, 1002L, 1005L, 1010L);
        return ResultUtils.success(hotItems.subList(0, Math.min(topN, hotItems.size())));
    }
}
